<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <div class='ele-cell workplace-user-card'>
        <div class='ele-cell-content ele-cell'>
          <a-progress :width='70' type='circle' :percent='100' :format="() => '柜子'" />
          <div class='ele-cell-content'>
            <h4 class='ele-elip'>设备号：{{ data.recordId }}</h4>
            <div class='ele-elip ele-text-secondary'>
              <clock-circle-outlined />
              <em>{{ data.deviceTime }}</em>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :model='form'
        :rules='rules'
        :label-col='{ md: { span: 10 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 14 }, sm: { span: 24 } }'
        @submit='saveConfigToCmdQueue'
      >
        <a-divider>总开关</a-divider>
        <a-row :gutter='8'>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='总开关' name='masterSwitch'>
              <a-switch
                checked-children='开'
                un-checked-children='关'
                autoFocus='false'
                :checked='switchform.masterSwitchCheck'
                @change='masterSwitchChange'
              />
            </a-form-item>
          </a-col>

          <a-col :md='12' :sm='24' :xs='24' />
        </a-row>
        <a-divider>转向相关参数</a-divider>
        <a-row :gutter='8'>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='转向判断依据' name='sourceSwitch'>
              <a-radio-group v-model:value='form.sourceSwitch'>
                <a-radio :value='1'>
                  仅靠堵转电流
                </a-radio>
                <a-radio :value='2'>
                  堵转电流或行程开关
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label='电机反转的待机间隔时间(秒):' name='standbyTime'>
              <a-input style="width: 70%" v-model:value='form.standbyTime' placeholder='单位秒,范围从3到600秒' allow-clear />
            </a-form-item>
            <a-form-item label='电机反转的相电流门限(安培):' name='sourceCurrent'>
              <a-input style="width: 70%" v-model:value='form.sourceCurrent' placeholder='精确到小数点后2位' allow-clear />
            </a-form-item>
            <a-form-item label='清粪一次的大致时间(秒):' name='durationCleanOnce'>
              <a-input style="width: 70%" v-model:value='form.durationCleanOnce' placeholder='单位秒' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24' />
        </a-row>

        <a-divider>防冻参数</a-divider>
        <a-row :gutter='8'>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='防冻模式' name='antifreezeMode'>
              <a-radio-group v-model:value='form.antifreezeMode'>
                <a-radio :value='1'>
                  关闭
                </a-radio>
                <a-radio :value='2'>
                  手动开启
                </a-radio>
                <a-radio :value='3'>
                  根据温度自动启停
                </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label='自动启停的温度阈值:' name='antifreezeStartRtt'>
              <a-input style="width: 70%" v-model:value='form.antifreezeStartRtt' placeholder='精确到小数点后1位' allow-clear />
            </a-form-item>
            <a-form-item label='防冻模式下的间隔时间(秒):' name='antifreezeInterval'>
              <a-input  style="width: 70%" v-model:value='form.antifreezeInterval' placeholder='单位秒' allow-clear />
            </a-form-item>
            <a-form-item label='防冻模式下每次动作的时长(秒):' name='antifreezeActionTime'>
              <a-input  style="width: 70%" v-model:value='form.antifreezeActionTime' placeholder='单位秒' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24' />
        </a-row>

        <a-divider>告警设置</a-divider>
        <a-row>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='温度报警下限(℃):' name='tempAlarmLow'>
              <a-input v-model:value='form.tempAlarmLow' placeholder='精确到小数点后1位,范围从-500到900' allow-clear />
              <a-alert message="精确到小数点后1位,范围从-500到900" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='温度报警上限(℃):' name='tempAlarmHigh'>
              <a-input v-model:value='form.tempAlarmHigh' placeholder='精确到小数点后1位,范围从-500到900' allow-clear />
              <a-alert message="精确到小数点后1位,范围从-500到900" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='三相电压告警下限:' name='voltageAlarmLow'>
              <a-input-number :min="80" :max="280" v-model:value='form.voltageAlarmLow' placeholder='范围从80到280' allow-clear />
              <a-alert message="范围从80到280,整数" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='三相电压告警上限:' name='voltageAlarmHigh'>
              <a-input-number :min="80" :max="280" v-model:value='form.voltageAlarmHigh' placeholder='范围从80到280' allow-clear />
              <a-alert message="范围从80到280,整数" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'>
            <a-form-item label='湿度报警下限(%RH):' name='humAlarmLow'>
              <a-input v-model:value='form.humAlarmLow' placeholder='精确到小数点后1位,范围从0到100' allow-clear />
              <a-alert message="精确到小数点后1位,范围从0到100" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='湿度报警上限(%RH):' name='humAlarmHigh'>
              <a-input v-model:value='form.humAlarmHigh' placeholder='精确到小数点后1位,范围从0到100' allow-clear />
              <a-alert message="精确到小数点后1位,范围从0到100" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='电流告警下限:' name='currentAlarmLow'>
              <a-input v-model:value='form.currentAlarmLow' placeholder='精确到小数点后2位' allow-clear />
              <a-alert message="精确到小数点后2位" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
            <a-form-item label='电流告警上限:' name='currentAlarmHigh'>
              <a-input v-model:value='form.currentAlarmHigh' placeholder='精确到小数点后2位' allow-clear />
              <a-alert message="精确到小数点后2位" style="margin-top:5px;font-size: 11px;padding:2px 3px;" type="info" show-icon />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md='1' :sm='24' :xs='24' />

          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_GLOBALCONFIG_SAVE_BUTTON']" type='primary' html-type='submit' :loading='iconLoading'>
                保存并同步
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_RESTART_BUTTON']" type='primary' html-type='button' @click='restartActionToCmdQueue' :loading='restartIconLoading'>
                重启设备
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_READ_CONFIG_BUTTON']" type='primary' html-type='button' @click='getParamsActionToCmdQueue' :loading='getParamsLoading'>
                读取设备的配置
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_CLEAR_CONFIG_SPRAY_EDIT_BUTTON']" type='primary' html-type='button' @click='clearParamsActionToCmdQueue' :loading='clearParamsLoading'>
                一键清除所有配置
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='1' :sm='24' :xs='24' />
          <a-col :md='2' :sm='24' :xs='24'>
            <a-form-item :wrapper-col='{ span: 12, offset: 5 }'>
              <a-button v-permission="['PROPERTY_DEVICELIST_MGR_SLURRY_CONFIG_READ_SIM_BUTTON']" type='primary' html-type='button' @click='getCcidToCmdQueue' :loading='getCcidLoading'>
                读取SIM卡信息
              </a-button>
            </a-form-item>
          </a-col>
          <a-col :md='9' :sm='24' :xs='24' />
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import ClockCircleOutlined from '@ant-design/icons-vue/lib/icons/ClockCircleOutlined';
import { message } from 'ant-design-vue';
import {DeviceSlurryScraperConfigApi} from "@/api/property/slurryscraper/DeviceSlurryScraperConfigApi";
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';


export default {
  name: 'DeviceSlurryscraperConfigSwitch',
  components: {
    ClockCircleOutlined
  },
  props: {
    data: Object
  },
  async mounted() {
  },
  async created() {
    await this.init();
  },
  data() {
    return {
      form: {},
      sourceForm: {},
      switchform: {},
      rules: {},
      iconLoading: false,
      loadTimer: null,

      restartIconLoading : false,
      restartLoadTimer : '',
      getParamsLoading : false,
      getParamsTimer : '',

      clearParamsLoading : false,
      clearParamsTimer : null,
      getCcidLoading : false,
      getCcidTimer : '',
    };
  },
  methods: {
    async init() {
      let _conf = await DeviceSlurryScraperConfigApi.detail({ 'recordId': this.data.recordId });
      if (_conf) {
        this.form = _conf;
        this.switchform.masterSwitchCheck = (_conf.masterSwitch == 1) ? true : false;
        console.log(this.form);
        this.sourceForm = Object.assign({}, _conf);
      }
    },
    masterSwitchChange(checked) {
      console.log(checked);
      this.switchform.masterSwitchCheck = checked;
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //保存配置
    clearConfigProcess(){
      this.iconLoading = false;
      clearInterval(this.loadTimer);
    },
    checkConfigProcess()
    {
      let that = this;
      this.checkProcess(21, this.clearConfigProcess, function(){
        that.init();
      });
    },
    saveConfigToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 21
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.save();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    /**
     * 保存和编辑
     * 写到队列，队列发送完回写到原配置
     * @author cancan
     * @date 2022/03/04 21:15
     */
    save() {
      this.form.masterSwitch = this.switchform.masterSwitchCheck ? 1 : 2;
      // 校验表单
      //await this.$refs.form.validate();

      // 修改加载框为正在加载
      this.loading = true;
      let updateForm = this.form;
      delete updateForm.heartIntervalTime;
      delete updateForm.runModel;
      delete updateForm.calnumModelConf;
      delete updateForm.timeModelConf;

      let updateData = {
        old: this.sourceForm,
        update: updateForm
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 21,
        sceneDictate : 21
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.iconLoading = true; //转圈
          this.loadTimer = setInterval(this.checkConfigProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },



    //重启命令
    clearRestartProcess(){
      this.restartIconLoading = false;
      clearInterval(this.restartLoadTimer);
    },
    checkRestartProcess()
    {
      let that = this;
      this.checkProcess(4, this.clearRestartProcess, function(){
        that.init();
      });
    },
    restartActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 4
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.restart();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    restart () { //重启
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };

      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 4,
        sceneDictate : 4
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.restartIconLoading = true; //转圈
          this.restartLoadTimer = setInterval(this.checkRestartProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },


    //读取参数
    clearGetParamsProcess(){
      this.getParamsLoading = false;
      clearInterval(this.getParamsTimer);
    },
    checkGetParamsProcess()
    {
      let that = this;
      this.checkProcess(56, this.clearGetParamsProcess, function(){
        that.init();
      });
    },
    getParamsActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 56
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.getParams();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    getParams() { //读取配置
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 56,
        sceneDictate : 56
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.getParamsLoading = true; //转圈
          this.getParamsTimer = setInterval(this.checkGetParamsProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },


    //清理配置
    clearClearParamsProcess(){
      this.clearParamsLoading = false;
      clearInterval(this.clearParamsTimer);
    },
    clearParamsProcess()
    {
      let that = this;
      this.checkProcess(9991, this.clearClearParamsProcess, function(){
        that.init();
      });
    },
    clearParamsActionToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 9991
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.clearParamsAction();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    clearParamsAction() { //读取配置
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 21,
        sceneDictate : 9991
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.clearParamsLoading = true; //转圈
          this.clearParamsTimer = setInterval(this.clearParamsProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //获取CCID begin------------
    clearGetCcidProcess(){
      this.getCcidLoading = false;
      clearInterval(this.getCcidTimer);
    },
    checkGetCcidProcess()
    {
      let that = this;
      this.checkProcess(38, this.clearGetCcidProcess, function(){
        that.init();
      });
    },
    getCcidToCmdQueue()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 38
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.getCcidRquest();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    getCcidRquest() { //读取配置
      this.loading = true;
      let updateData = {
        old: '',
        update: '',
      };
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'scraper',
        updateData: JSON.stringify(updateData),
        dictate : 38,
        sceneDictate : 38
      };

      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          // 移除加载框
          this.loading = false;
          // 提示添加成功
          message.success(result.message);

          this.getCcidLoading = true; //转圈
          this.getCcidTimer = setInterval(this.checkGetCcidProcess, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //获取CCID end---------------
  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
